﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace kiosk
{
    public partial class GBTextInput : Form
    {
        
        private bool nonNumberEntered = false;
        private List<ListViewItem> mListItem;
        private List<string> lanNames;
        private Int32 GroupID =-1;
        private ListViewItem selection;
        private DataBaseHandler handler;
        private List<Item> items;
        private Int32 nBtnAdd;
        public GBTextInput()
        {
            InitializeComponent();
            mListItem = new List<ListViewItem>();
            this.handler = new DataBaseHandler();
            this.handler.parpreConn();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        }
        
        public GBTextInput(Int32 gid)
        {
            this.GroupID = gid;
            InitializeComponent();
            mListItem = new List<ListViewItem>();
            this.handler = new DataBaseHandler();
            this.items = new List<Item>();
            this.handler.parpreConn();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

        }
       
        private void GBTextInput_Load(object sender, EventArgs e)
        {

            

            if (this.GroupID == -1)
            {

                DataBaseHandler handler = new DataBaseHandler();
                try
                {
                    
                    
                    this.lanNames = handler.getAllLanguageNames();
                
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "internal error proper group is not set please contract admin", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                this.mListView.View = View.Details;
                // this.mListView.Columns.Add("       ");
                this.mListView.Columns.Add("Language");
                this.mListView.Columns.Add("Button text");

                foreach (string str in lanNames)
                {
                    mListItem.Add(new ListViewItem(str));
                    this.mListView.Items.Add(mListItem[mListItem.Count - 1]);

                }
               

            }
            else
            {
                
                this.mListView.View = View.Details;

                this.mListView.Columns.Add("Language");
                this.mListView.Columns.Add("On Button");
                this.mListView.Columns.Add("Button Text");

               
                   
            }
                
            this.SetupCboButton();
           
       


        }

     

       

        private void glassButton5_Click(object sender, EventArgs e)
        {

            // DataBaseHandler handler = new DataBaseHandler();

            if(this.NBtnText.Text == "")
            {
                MessageBox.Show("Please enter number of button have to created in each language", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }

            if(this.BtnTextCbo.SelectedIndex == -1 && this.GroupID != -1)
            {
                MessageBox.Show("Please select a Label Name from the dropdown box");
                return;
            
            }

            if (this.GroupID == -1)   // To be fixed
            {

                // if the editing mode on the first page of the application
           

                    Int32 noofbitt = Convert.ToInt32(this.NBtnText.Text);
                    this.nBtnAdd = noofbitt;
                    int i = 0;
                    this.mListItem.Clear();
                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                    DisplayOption opt = new DisplayOption();
                    
                
                   // If there is no primargroup 
                    List<int> btnGroup = this.handler.getPrimaryBtnGroup();
                    if (btnGroup == null)
                    {
                        foreach (string str in this.lanNames)
                        {
                            for (; i < noofbitt; i++)
                            {
                                this.mListItem.Add(new ListViewItem(new String[] { str, "Button text" }));
                                Font font = (Font)converter.ConvertFromString(opt.DefaultFont);

                                this.mListItem[this.mListItem.Count - 1].Font = font;


                            }
                            i = 0;

                        }



                    }
                    else
                    { 
                       //// the primarigroup has items

                       // DataTable dt;
                       // foreach (Int32 gid in btnGroup)
                       // {
                       //     dt = this.handler.getAllGroupItems(gid);
                        
                       // }

                    
                    
                    }
                    this.mListView.Items.Clear();
                    this.mListView.Items.AddRange(mListItem.ToArray<ListViewItem>());
                    this.mListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    this.mListView.Refresh();

                    ColumnHeader[] mlist = new ColumnHeader[1];
                    mlist[0] = this.mListView.Columns[0];
                    this.mListView.GroupBy(mlist);
                    this.mListView.View = View.Details;
                    this.mListView.GridLines = true;
                


                
            }
            
            else {
                // if a group id is given 
               // MessageBox.Show("This group id" + this.GroupID.ToString());
               
                try
                {
                    this.lanNames = handler.getAllLanguageNames();
                   
                }
                catch(Exception ex)
                {

                    MessageBox.Show(ex.Message + "internal error proper group is not set please contract admin", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                Int32 noofbitt = Convert.ToInt32(this.NBtnText.Text);
                this.nBtnAdd = noofbitt;
                int i = 0 , j=0;;
                this.mListItem.Clear();
                string cboText = Convert.ToString(this.BtnTextCbo.SelectedItem);
                List<ExtItem> related = null;
                
                try
                {
                    int itemID = this.handler.getItemId(cboText);
                    related = this.handler.getRelatedItemBtns(itemID);



                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }

                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));

                foreach (string str in this.lanNames)
                {
                    for (; i < noofbitt; i++)
                    {
                        this.mListItem.Add(new ListViewItem(new String[] { str, related[j].ItemText, "Button text" }));
                        this.mListItem[this.mListItem.Count - 1].Font = (Font)converter.ConvertFromString(related[j].Font);

                    }
                    i = 0;
                    j++;
                }
                this.mListView.Items.Clear();
                this.mListView.Items.AddRange(mListItem.ToArray<ListViewItem>());
                this.mListView.Refresh();
                ColumnHeader[] mlist = new ColumnHeader[1];
                mlist[0] = this.mListView.Columns[0];
                this.mListView.GroupBy(mlist);
                this.mListView.View = View.Details;
              }
            this.mListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            this.mListView.Refresh();

        }

        private void NBtnText_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;
            }


        }

        private void NBtnText_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }

        }

        private void mListView_MouseDown(object sender, MouseEventArgs e)
        {

            if (selection != null)
            {
                selection.BackColor = Color.White;
            }
            selection = this.mListView.GetItemAt(e.X, e.Y);

            // If the user selects an item in the ListView, display
            
            if (selection != null)
            {
                if (GroupID == -1)
                    this.BtnText.Text = selection.SubItems[1].Text;
                else
                   this.BtnText.Text = selection.SubItems[2].Text;
                
                selection.BackColor = Color.DimGray;
                this.BtnText.Font = this.selection.Font;
            }

        
        }

        private void STexBtn_Click(object sender, EventArgs e)
        {
            if (this.selection != null)
            {
                if(this.BtnText.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter label text !!");
                    return;
                
                }

                if (this.GroupID == -1)
                    selection.SubItems[1].Text = this.BtnText.Text.Trim();
                else
                    selection.SubItems[2].Text = this.BtnText.Text.Trim();
            }


        }

        private void txtFontSetup_Click(object sender, EventArgs e)
        {
            if (this.selection == null)
            {
                MessageBox.Show("You Must select a Label !! ");
                return;
            
            }
            if (fontDialog1.ShowDialog() != DialogResult.Cancel)
            {
                  this.BtnText.Font = fontDialog1.Font;
                  this.selection.Font = fontDialog1.Font;
                  MessageBox.Show(this.selection.Font.ToString());
             //   this.BtnText.ForeColor = fontDialog1.Color;
            
              // also modify the item col in the item list view

            }

            
        }

        private void CreateBtn_Click(object sender, EventArgs e)
        {
            if (this.mListView.Items.Count == 0)
            {
                MessageBox.Show("Add some items (Use the add key)", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }
                                
            // If the first screen in whuich the ctrl+g is pressed
          
            // get all the text from the listbox

            if (this.GroupID == -1)
            {
                ListView.ListViewItemCollection itv = this.mListView.Items;
                Int32 noofbitt = Convert.ToInt32(this.NBtnText.Text);
                this.nBtnAdd = noofbitt;

                bool dupLicateLabel = false;
                List<Int32> groupList = null;

                try
                {
                    if (!handler.isgroupTableEmpty())
                    {
                        // to be fixed it has errors (Concept the first page in  the system)(check my be solved)
                       
                        groupList = handler.getPrimaryBtnGroup();
                   
                    }
                    else
                    {
                        groupList = this.handler.createBtnGroup();
                    
                    }
                    
                    List<List<ExtItem>> items = this.createItemList(1);
                   ///Logic for the duplicate entry
                   ///
                    
                    //List<ExtItem> dup = new List<ExtItem>();
                    //foreach (List<ExtItem> item in items)
                    //{
                    //    dup.AddRange(item.ToArray<ExtItem>());

                    //}
                    foreach (List<ExtItem> ib in items)
                    {
                        int total = ib.Count;
                        for (int i = 0; i < total; i++)
                        {
                            for (int j = total - 1; j > i; j--)
                            {

                                if (String.Equals(ib[j - 1].ItemText, ib[j].ItemText, StringComparison.OrdinalIgnoreCase))
                                {
                                    MessageBox.Show("Duplicate button label is not allowed Found :" + ib[j - 1].ItemText + " And " + ib[j].ItemText);
                                    dupLicateLabel = true;
                                    break;


                                }

                            }




                        }



                    }


                        if (dupLicateLabel)
                        {
                            return;

                        }




                    // The error handel of in the next group there is already an items

                        if (!handler.isgroupTableEmpty())
                        {
                            // to be fixed it has errors (Concept the first page in  the system)(check my be solved)
                            int relativeIndex = 0;
                            List<Int32> tempGid = this.handler.getPrimaryBtnGroup();

                            foreach (int gids in tempGid)
                            {

                                DataTable dt = this.handler.getAllGroupItems(gids);
                                if (dt.Rows.Count > 0)
                                {
                                    dupLicateLabel = false;
                                    for (int j = 0; j < items[relativeIndex].Count; j++)
                                    {

                                        foreach (DataRow row4 in dt.Rows)
                                        {

                                            if (String.Equals(items[relativeIndex][j].ItemText, (String)row4["ItemText"], StringComparison.OrdinalIgnoreCase))
                                            {
                                                MessageBox.Show("Duplicate button label is not allowed !!! There is an Duplicate label on the \r\n label that you have selected (The Seleted label already has Labes that contains the label you have entered !!):" + items[relativeIndex][j].ItemText + " And " + (String)row4["ItemText"]);
                                                dupLicateLabel = true;


                                            }



                                        }


                                    }





                                }





                                relativeIndex++;

                            
                            }







                        }


                    //------------------------------------------------------------------
                       

                    this.handler.createitemInGroup(groupList, items);
                   
                    MessageBox.Show("The Buttons are created sucessfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //this.mListView.Refresh();
                    this.Close();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                
            }
            else
            {
                // The call was made from an populated window so we have to fix the parent relationship

                ListView.ListViewItemCollection itv = this.mListView.Items;
                Int32 noofbitt = Convert.ToInt32(this.NBtnText.Text);
                this.nBtnAdd = noofbitt;
                List<Int32> groupList = null;
                try
                {

                    groupList = this.handler.createBtnGroup();
                    List<List<ExtItem>> items = this.createItemList(2);
                    this.handler.createitemInGroup(groupList, items);
                    
                    int row = 0;
                    
                    string cboItName = Convert.ToString(this.BtnTextCbo.SelectedItem);
                    // for better implementation we should use the tag in the cbobox (Use Mvc approach)
                    IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                    Int32[] itr = id.ToArray<Int32>();
                    List<ExtItem> rit = this.handler.getRelatedItemBtns(itr[0]);
                    
                    /// Checking for any duplicate iTemTexT in the subitems group on which the Items will be pushed
                    /// 
                  
                    int groupid;

                    bool dupLicateLabel = false;

                    //            if (String.Equals(it.ItemText, checkRow[i].ItemText, StringComparison.OrdinalIgnoreCase))

                    #region dupItemFinder
                    //List<ExtItem> dup = new List<ExtItem>();
                    //foreach (List<ExtItem> item in items)
                    //{ 
                    //   dup.AddRange(item.ToArray<ExtItem>());
                    
                    //}

                    // BAd Algorithm
                    //int total = dup.Count;
                    //for (int i = 0; i < total; i++)
                    //{
                    //    for (int j = total - 1; j > i;j-- )
                    //    {

                    //        if (String.Equals(dup[j -1].ItemText, dup[j].ItemText, StringComparison.OrdinalIgnoreCase))
                    //        {
                    //            MessageBox.Show("Duplicate button label is not allowed Found :" + dup[j - 1].ItemText + " And " + dup[j].ItemText);
                    //            dupLicateLabel = true;
 
                            
                    //        }

                    //    }
                    
                    
                    
                    
                    //}

                    foreach (List<ExtItem> ib in items)
                    {
                        int total = ib.Count;
                        for (int i = 0; i < total;i++ )
                        {
                            for (int j = total - 1; j > i;j-- )
                            {

                                 if (String.Equals(ib[j -1].ItemText, ib[j].ItemText, StringComparison.OrdinalIgnoreCase))
                                 {
                                     MessageBox.Show("Duplicate button label is not allowed Found :" + ib[j - 1].ItemText + " And " + ib[j].ItemText);
                                     dupLicateLabel = true;
                                     break;


                                 }

                            }


                            

                        }


                    
                    }


                     if (dupLicateLabel)
                        {
                            return;

                        }


                     #endregion dupitemFinder

          
                    
                    
                    // xheck to see if there is any of the button that has a data alredy
                    int dataid;
                    foreach (ExtItem it in rit)
                    {
                         dataid = this.handler.isItemDataPresent(it.ItemID);
                        if (dataid != -1)
                        {
                            if (MessageBox.Show("The label you selected already contains ( And in the other languages) a viewable data !! \n If you continue the all those viewable data will be deleted. Do you wish to continue ?? ", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                // then delete all those dataitems 
                                this.handler.dTextData(it.ItemID);
                                // set the dataId = null
                                this.handler.setDataIDTONull(it.ItemID);

                            }
                            else
                            {
                                MessageBox.Show("Quiting not saving anything !!");
                                return;

                            }
                        }
                     
                    }


                    // Check if the Item selecyted in the cbo Display group alreary cintains a item name entered

                  //foreach (ExtItem it in rit)
                  //{
                  //    int disGroup = this.handler.getDisplayGroup(it.ItemID);
                  //    if (disGroup != -1)
                  //    {
                  //        DataTable dt = this.handler.getAllGroupItems(disGroup);
                  //        if (dt.Rows.Count > 0)
                  //        {

                  //            dupLicateLabel = false;
                  //            foreach (ExtItem myitem in dup)
                  //            {
                  //                foreach (DataRow myrow in dt.Rows)
                  //                {

                  //                    if (String.Equals(myitem.ItemText, (String)myrow["ItemText"], StringComparison.OrdinalIgnoreCase))
                  //                    {
                  //                        MessageBox.Show("Duplicate button label is not allowed !!! There is an Duplicate label on the \r\n label that you have selected (The Seleted label already has Labes that contains the label you have entered !!):" + myitem.ItemText + " And " + (String)myrow["ItemText"]);
                  //                        dupLicateLabel = true;


                  //                    }


                  //                }
                  //            }
                  //            if (dupLicateLabel)
                  //            {
                  //                return;

                  //            }



                  //        }
                      
                  //    }
                  
                  
                  
                  //}


                    // New algorithm of the problem
                    int relativeIndex = 0;
                    foreach(ExtItem it in rit)
                    {
                        
                        int disGroup = this.handler.getDisplayGroup(it.ItemID);

                        if (disGroup != -1)
                        {

                            DataTable dt = this.handler.getAllGroupItems(disGroup);
                            if(dt.Rows.Count > 0)
                            {
                                dupLicateLabel = false;
                                for (int j = 0; j < items[relativeIndex].Count; j++)
                                {
                                   
                                    foreach(DataRow row4 in dt.Rows )
                                    {

                                        if (String.Equals(items[relativeIndex][j].ItemText, (String)row4["ItemText"], StringComparison.OrdinalIgnoreCase))
                                        {
                                            MessageBox.Show("Duplicate button label is not allowed !!! There is an Duplicate label on the \r\n label that you have selected (The Seleted label already has Labes that contains the label you have entered !!):" + items[relativeIndex][j].ItemText + " And " + (String)row4["ItemText"]);
                                            dupLicateLabel = true;


                                        }
                                    
                                    
                                    
                                    }


                                }
                               

                                                
                              
                            
                            }


                        
                        
                        
                        
                        }



                        relativeIndex ++;
                    
                    }

                   
                    if (dupLicateLabel)
                    {
                        return;

                    }









                    foreach (Int32 gid in groupList)
                    {
                         groupid = this.handler.getGroupIDOnItemID(rit[row].ItemID);
                        this.handler.updateParentGID(gid, groupid);
                        this.handler.updateDisplayGroup(rit[row].ItemID , gid );
                        row++;

                    }
                    
                    MessageBox.Show("The Buttons are created sucessfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //this.mListView.Refresh();
                    this.Close();
                
                }
                catch (Exception ex)
                {

                    MessageBox.Show("There was an error in creating Buttons the Error message is :" + ex.Message);

                }

                
            }
        
        }

        // testing if there is maney buttons are there

        private void SetupCboButton()
        {
            if (this.GroupID == -1) {

                if (!handler.isgroupTableEmpty())
                {
                    // to be fixed it has errors (Concept the first page in  the system)(check my be solved)
                   // please select the language
                    if (this.lanNames == null)
                        this.lanNames = this.handler.getAllLanguageNames();
                    foreach (string str in this.lanNames)
                        this.BtnTextCbo.Items.Add(str);



                }
                else
                {
                    this.BtnTextCbo.Items.Add("Just add some buttons ^-^");
                   
                }
                return;
            }
                

           
            DataTable dt;
            try {
                dt = this.handler.getAllGroupItems(this.GroupID);
                foreach (DataRow row in dt.Rows)
                {
                    items.Add(new Item());
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (col.ColumnName == "ItemText")
                        {
                            this.items[this.items.Count - 1].ItemText = Convert.ToString(row[col]).Trim();

                        }
                        if (col.ColumnName == "ItemID")
                        {
                            this.items[this.items.Count - 1].ItemID = Convert.ToInt32(row[col]);
 
                        }

                    }
                }

                foreach (Item it in this.items)
                {
                    this.BtnTextCbo.Items.Add(it.ItemText);
                
                }


            }
            catch(Exception ex)
            {
                
                MessageBox.Show(ex.Message + "internal error proper group is not set please contract admin", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

             }


      }

        private void BtnTextCbo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // when combo changes we have to change the On button column in the listview object

            if (this.GroupID == -1)
                return;
            
            if (this.mListView.Items.Count < 1)
            {
                return;
            
            }
            string cboItName = Convert.ToString( this.BtnTextCbo.SelectedItem);
          
            List<ExtItem> it =null;

            try {
                IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c=> c.ItemID);
                Int32[] itr = id.ToArray<Int32>() ;
                it = this.handler.getRelatedItemBtns(itr[0]);
            
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message +" There was an unexcepted error please contract admin");
            
            }

            
            Int32 row =0;
            foreach (Item data in it)
            {
                for(int j=0;j<this.nBtnAdd;j++,row++)
                {
                    this.mListView.Items[row].SubItems[1].Text = data.ItemText.Trim();
                
                }
            
            
            }
            //this.mListView.RedrawItems();
            this.mListView.Refresh();


    }


        private List<List<ExtItem>> createItemList(int subID)
        {

            List<List<ExtItem>> lists = new List<List<ExtItem>>();
            int totalNum = this.mListView.Items.Count / this.nBtnAdd;
            // Get the items from the lists 
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));

            int it = 0;
            for (int i = 0; i < totalNum; i++)
            {
                lists.Add(new List<ExtItem>());
                for (int j = 0; j < this.nBtnAdd; j++)
                {
                    
                    lists[i].Add(new ExtItem());
                    
                    
                    lists[i][j].ItemText = this.mListView.Items[it].SubItems[subID].Text.Trim();
                   
                    string fstring = converter.ConvertToString(this.mListView.Items[it].Font);
                  
                    lists[i][j].Font = fstring;
                    it++;
                
                }
               
            
            }


                return lists;

        
        }

        private void BtnText_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar == (char)13)
            {


                if (this.selection != null && this.BtnText.Text.Trim() != String.Empty)
                {
                    
                    /*
                     *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                        Int32[] itr = id.ToArray<Int32>();
                     * 
                     * */
                    if (this.GroupID == -1)
                        selection.SubItems[1].Text = this.BtnText.Text.Trim();
                    else
                        selection.SubItems[2].Text = this.BtnText.Text.Trim();

                }



            } // end of the keycode





        }

        private void BtnText_Leave(object sender, EventArgs e)
        {

            if (this.selection != null && this.BtnText.Text.Trim() != String.Empty)
            {
                
                /*
                 *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                    Int32[] itr = id.ToArray<Int32>();
                 * 
                 * */
                if (this.GroupID == -1)
                    selection.SubItems[1].Text = this.BtnText.Text;
                else
                    selection.SubItems[2].Text = this.BtnText.Text;


            }




        }

      



 }

}
